import dayjs, { Dayjs } from "dayjs";
import { jsonCopy, nullC, numberC, isValue } from "./common";
import { imgApi } from "@/http/api";
import { h } from "vue";

/**
 *@Author: QWP
 *@Description: 金额千分位的转换
 *@Params: num: 要转换的数据    len: 保留小数位数
 *@Date 2023-06-18 12:43
 */
export function formatAmt(num, len = 2) {
  if (parseFloat(num) == 0) {
    return parseFloat(num).toFixed(2);
  } else if (num == undefined) {
    return "";
  } else {
    num += "";
    if (!num.includes(".")) {
      num += ".";
    }
    let tempNum = parseFloat(num)
      .toFixed(len)
      .replace(/(\d)(?=(\d{3})+\.)/g, "$1,")
      .replace(/(0+)$/g, "");
    if ((tempNum.indexOf(".") != -1 && tempNum.split(".")[1].length == 0) || tempNum.indexOf(".") == -1) {
      tempNum = tempNum + "00";
    }
    return tempNum;
  }
}

/**
 *@Author: QWP
 *@Description: 金额转大写
 *@Params: money: 要转换的原始数据
 *@Date 2023-10-07 17:57
 */
export const formatBigAmt = (money) => {
  var cnNums = new Array("零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"); //汉字的数字
  var cnIntRadice = new Array("", "拾", "佰", "仟"); //基本单位
  var cnIntUnits = new Array("", "万", "亿", "兆"); //对应整数部分扩展单位
  var cnDecUnits = new Array("角", "分", "毫", "厘"); //对应小数部分单位
  var cnInteger = "整"; //整数金额时后面跟的字符
  var cnIntLast = "元"; //整数完以后的单位
  //最大处理的数字
  var maxNum = 999999999999999.9999;
  var integerNum; //金额整数部分
  var decimalNum; //金额小数部分
  //输出的中文金额字符串
  var chineseStr = "";
  var parts; //分离金额后用的数组，预定义
  if (money == "") {
    return "";
  }

  money = parseFloat(money);
  if (money >= maxNum) {
    //超出最大处理数字
    return "超出最大处理数字";
  }
  if (money == 0) {
    chineseStr = cnNums[0] + cnIntLast + cnInteger;
    return chineseStr;
  }
  //四舍五入保留两位小数,转换为字符串
  money = Math.round(money * 100).toString();
  integerNum = money.substr(0, money.length - 2);
  decimalNum = money.substr(money.length - 2);
  //获取整型部分转换
  if (parseInt(integerNum, 10) > 0) {
    var zeroCount = 0;
    var IntLen = integerNum.length;
    for (var i = 0; i < IntLen; i++) {
      var n = integerNum.substr(i, 1);
      var p = IntLen - i - 1;
      var q = p / 4;
      var m = p % 4;
      if (n == "0") {
        zeroCount++;
      } else {
        if (zeroCount > 0) {
          chineseStr += cnNums[0];
        }
        //归零
        zeroCount = 0;
        chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
      }
      if (m == 0 && zeroCount < 4) {
        chineseStr += cnIntUnits[q];
      }
    }
    chineseStr += cnIntLast;
  }
  //小数部分
  if (decimalNum != "") {
    var decLen = decimalNum.length;
    for (var i = 0; i < decLen; i++) {
      var n = decimalNum.substr(i, 1);
      if (n != "0") {
        chineseStr += cnNums[Number(n)] + cnDecUnits[i];
      }
    }
  }
  if (chineseStr == "") {
    chineseStr += cnNums[0] + cnIntLast + cnInteger;
  } else if (decimalNum == "" || /^0*$/.test(decimalNum)) {
    chineseStr += cnInteger;
  }
  return chineseStr;
};

/**
 *@Author: QWP
 *@Description: 取消金额千分位 ———— 转为数字
 *@Params: num: 要转换的数据    len: 保留小数位数
 *@Date 2023-06-18 12:43
 */
export function cancelAmt(num, len = 2) {
  if (!num) {
    return 0;
  }

  return numberC(`${num}`.replace(/,/g, ""));
}

/**
 *@Author: QWP
 *@Description: 格式化下拉的树形数据
 *@Params: data
 *@Date 2023-08-23 11:11
 */
export const formtTreeData = (data = [], pkey = "text", pValue = "全部") => {
  let data1 = data[0][pkey] == pValue ? JSON.parse(JSON.stringify(data[0]["children"])) : JSON.parse(JSON.stringify(data));
  if (data1 instanceof Array == false) {
    data1 = JSON.parse(JSON.stringify(data));
  }

  let formatTree = (data2 = []) => {
    data2.forEach((item) => {
      if (!item?.children) {
        item.leaf = "leaf";
        delete item.children;
      } else if (item?.children?.length == 0) {
        item.leaf = "leaf";
        delete item.children;
      } else {
        formatTree(item.children);
      }
    });
  };
  formatTree(data1);
  return data1;
};

/**
 *@Author: QWP
 *@Description: 格式化列表数据的echo枚举数据
 *@Date 2023-08-29 15:24
 */
export const formtTableEcho = (data) => {
  let tdata = JSON.parse(JSON.stringify(data));
  tdata.forEach((item) => {
    if (item.echo) {
      for (let key in item.echo) {
        item[key + "_echo"] = item.echo[key];
      }
    }
  });
  return tdata;
};

/**
 *@Author: QWP
 *@Description: 格式化列表数据的枚举数据
 *@Date 2023-08-29 15:24
 */
export const formtTableEnum = (data, tabData, key, props = { label: "name", id: "id" }) => {
  let tdata = JSON.parse(JSON.stringify(tabData));
  tdata.forEach((item) => {
    let filterData = data.filter((enumI) => `${nullC(item[key])}`.split(",").includes(`${nullC(enumI[props["id"]])}`));
    item[key + "_echo"] = filterData.map((i) => i[props.label]).join(",");
  });
  return tdata;
};

/**
 *@Author: QWP
 *@Description: 树形禁用指定类型的数据
 *@Params: params
 *@Date 2023-09-01 16:47
 */
export const formatTreeDis = (data, params = {}) => {
  let tdata = JSON.parse(JSON.stringify(data));
  const keys = Object.keys(params);
  if (keys.length != 0) {
    const tFormat = (pdata) => {
      pdata.forEach((item) => {
        keys.forEach((key) => {
          if (item[key] && item[key] == params[key]) {
            item.disabled = true;
          }
        });
        if (item.children) {
          tFormat(item.children);
        }
      });
    };
    tFormat(tdata);
  }

  return tdata;
};

/**
 *@Author: QWP
 *@Description: 禁用当前选中的数据
 *@Params: data, value 匹配数据， id = 'keyid', 匹配字段
 *@Date 2023-09-04 17:34
 */
export const disableTreeKeyid = (data, value, id = "keyid") => {
  let finData = JSON.parse(JSON.stringify(data));
  const dis = (tdata) => {
    tdata.forEach((item) => {
      if (item[id] == value) {
        item.disabled = true;
      } else if (item.children) {
        dis(item.children);
      }
    });
  };
  dis(finData);

  return finData;
};

/**
 *@Author: QWP
 *@Description: 禁用当前选中的数据
 *@Params: data, value 匹配数据数组， id = 'keyid', 匹配字段
 *@Date 2023-09-04 17:34
 */
export const disableTreeKeyids = (data, value = [], id = "keyid") => {
  let finData = JSON.parse(JSON.stringify(data));
  const dis = (tdata) => {
    tdata.forEach((item) => {
      if (value.includes(item[id])) {
        item.disabled = true;
      } else if (item.children) {
        dis(item.children);
      }
    });
  };
  dis(finData);

  return finData;
};

/**
 *@Author: QWP
 *@Description: 根据id获取元素对象
 *@Params: data1: 源数据   keyids: 目标id      targetKey: 要获取的字段
 *@Date 2023-09-12 15:18
 */
export const getDataIdById = (data1, keyids = [], targetKey = "keyid") => {
  let data = [];
  const get = (tdata) => {
    tdata.forEach((item) => {
      if (keyids.includes(item[targetKey])) {
        data.push(item);
      }
      if (item.children) {
        get(item.children);
      }
    });
  };

  get(data1);
  return data;
};

/**
 *@Author: QWP
 *@Description: 数组分组
 *@Date 2023-09-20 20:26
 */
export const groupBy = (array, f) => {
  var groups = {};
  array.forEach(function (o) {
    var group = JSON.stringify(f(o));
    groups[group] = groups[group] || [];
    groups[group].push(o);
  });
  return Object.keys(groups).map(function (group) {
    return groups[group];
  });
};

/**
 *@Author: QWP
 *@Description: 数组分组
 *@Date 2023-09-20 20:26
 */
export const groupBy1 = (array, key, isFormat = true) => {
  var groups = {};
  array.forEach(function (o) {
    if (o[key]) {
      groups[o[key]] = groups[o[key]] || [];
      groups[o[key]].push(o);
    }
  });
  return isFormat
    ? Object.keys(groups).map(function (group) {
        return groups[group];
      })
    : groups;
};

/**
 *@Author: QWP
 *@Description: 将下拉枚举的id转为数字型
 *@Params: data: 转换数据    key: 转换字段
 *@Date 2023-09-22 16:54
 */
export const turnEnumKeyToNum = (data, key = "id") => {
  data.forEach((item) => (item[key] = numberC(item[key])));
  return data;
};

/**
 *@Author: QWP
 *@Description: 递归赋值
 *@Params: data: 转换数据    key: 转换字段
 *@Date 2023-09-22 16:54
 */
export const deepForValue = (data, key, f) => {
  let tData = jsonCopy(data);
  const deepF = (td) => {
    td.forEach((item) => {
      item[key] = f(item);
      if ((item.children || []).length != 0) {
        deepF(item.children);
      }
    });
  };
  deepF(tData);
  return tData;
};

/**
 *@Author: QWP
 *@Description: 根据id获取元素
 *@Params: data: 源数据    ids: 目标数据   props: 树形参数
 *@Date 2023-09-25 10:14
 */
export const getItemByIds = (data, ids = [], props = { id: "keyid" }) => {
  let result = [];
  const get = (data1) => {
    data1.forEach((item) => {
      ids.forEach((i) => {
        if (i == item[props["id"]]) {
          result.push(item);
        }
      });
      if (item.children) {
        get(item.children);
      }
    });
  };
  get(data);

  return result;
};

/**
 *@Author: QWP
 *@Description: 数组拆分
 *@Params: array 数组源    chunkSize: 子数组大小
 *@Date 2024-05-21 15:09
 */
export const chunkArray = (array, chunkSize) => {
  let result = [];
  for (let i = 0; i < array.length; i += chunkSize) {
    result.push(array.slice(i, i + chunkSize));
  }
  return result;
};

/**
 *@Author: QWP
 *@Description: 防抖
 *@Date 2024-05-21 18:57
 */
export const debounce = (fn, wait) => {
  let timeout = null;
  return function () {
    let context = this;
    let args = arguments;
    if (timeout) clearTimeout(timeout);
    let callNow = !timeout;
    timeout = setTimeout(() => {
      timeout = null;
    }, wait);
    if (callNow) fn.apply(context, args);
  };
};

/**
 *@Author: QWP
 *@Description: 节流
 *@Date 2024-05-21 18:56
 */
export const throttle = (fn, wait) => {
  let previous = 0;
  return function () {
    let context = this;
    let args = arguments;
    let now = new Date();
    if (now - previous > wait) {
      fn.apply(context, args);
      previous = now;
    }
  };
};

// 格式化审核打印人员
export const formatAuditUserSign = (orignData, form) => {
  let tForm = jsonCopy(form);
  // 1 已提交  2 审核通过   3 退回   4 撤回
  const tabdata = jsonCopy(orignData).filter((item) => [1, 2].includes(item.auditstatus));
  // let result = groupBy1(tabdata, 'printposition')
  let result = {};
  tabdata.forEach((i) => {
    let printposition = `${i["printposition"]}`.split(",");
    printposition.forEach((k) => {
      if (!result[k]) {
        result[k] = [];
      }
      result[k].push(i);
    });
  });
  for (let key in result) {
    const item = result[key];
    // 一般人员
    if (key == "1") {
      tForm["shr" + key] = Array.from(new Set(item.map((i) => i.reusername))).join("<br/>");
    } else {
      let signs = Array.from(new Set(item.map((i) => i.signPosition)))
        .map((i) => {
          let signPosition = `${nullC(i)}`;
          if (signPosition) {
            return signPosition.indexOf("127.0") != -1 ? signPosition.replace(/^http:\/{2}\d+.\d+.\d+.\d+/g, fileDownload) : signPosition;
          } else {
            return "";
          }
        })
        .filter((i) => isValue(i));
      tForm["shr" + key] = signs;
    }
  }
  return tForm;
};

// 格式化页面的审核状态
export const formatStatus = (text, record = {}) => {
  const status = {
    "1": { textColor: "#FA8C16 ", bgColor: "rgba(250,140,22,0.2)", label: "未提交" },
    "2": { textColor: "rgba(24,144,255,1)", bgColor: "rgba(24,144,255,0.2)", label: "审核中" },
    "3": { textColor: "#52C41A", bgColor: "rgba(82,196,26,0.2)", label: "审核完成" },
    "4": { textColor: "#F5222D ", bgColor: "rgba(245,34,45,0.2)", label: "已退回" },
  };

  const res = status[record["status"]] || {};

  return h(
    "div",
    {
      style: {
        display: "inline-block",
        width: "max-content",
        padding: "0 8px",
        borderRadius: "4px",
        background: nullC(res["bgColor"]),
        color: nullC(res["textColor"]),
      },
    },
    res["label"] || ""
  );
};

// 格式化弹窗文字
export const formatDialogTitle = (record = {}) => {
  return ["2", "3"].includes(record["status"] + "") ? "" : "编辑";
};

/**
 *@Author: QWP
 *@Description: 日期禁用
 *@Params: current  当前日历日期   data: 禁用的日期边界   type:  'before' 禁用前面数据   after: '禁用后面数据
 *@Params: data 如果是数组，长度为2, 则分别禁用前后数据
 *@Date 2024-05-21 18:56
 */
export const disabledDateC = (current, data = [], type) => {
  if (!current) return false;
  let tData = data.filter((i) => isValue(i));
  if (tData.length > 1) {
    tData = tData.sort((a, b) => dayjs(b) - dayjs(b));
  }
  if (tData.length == 1) {
    if (type == "before") {
      return current < dayjs(tData[0]).endOf("day").subtract(1, "day");
    } else {
      return current > dayjs(tData[0]).endOf("day");
    }
  } else {
    return current < dayjs(tData[0]).endOf("day").subtract(1, "day") || current > dayjs(tData[1]).endOf("day");
  }
};

// 格式回显枚举
export const formatEnum = (text, enums = [], mode = "single") => {
  if (mode != "single") {
    let infos = enums.filter((i) => (text || "").split(",").includes(i.value + ""));
    return infos.map((i) => i.label).join(",");
  }
  let info = enums.find((i) => i.value == text);
  return info ? info["label"] : "";
};

// 扁平化树形数组
export const flatArr = (data) => {
  const results = [];
  const flat = (tData) => {
    tData.forEach((item) => {
      if ((item["children"] || []).length == 0) {
        results.push(item);
      } else {
        flat(item["children"] || []);
      }
    });
  };
  flat(data || []);

  return results;
};

// 修改图片访问地址
export const formatImgUrl = (url: string): string => {
  let reg = /^(http|https):\/\/\d+\.\d+\.\d+\.\d+(:\d+)?/;
  console.log("🚀 ~ formatImgUrl ~ (url ?? '').replace(reg, imgApi):", (url ?? "").replace(reg, imgApi));
  return (url ?? "").replace(reg, imgApi);
};
